package com.wolfpire.profession.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.profession.dao.ProfessionDao;
import com.wolfpire.system.common.Constants;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.system.common.util.MatchType;
import com.wolfpire.system.model.DataDict;
import com.wolfpire.system.model.Notice;
import com.wolfpire.system.model.Profession;
import com.wolfpire.system.model.User;
@Repository("professionDao")
public class ProfessionDaoImpl extends BaseHibernateDao<Profession, Long> implements 
	ProfessionDao {
	/**
	 * 根据专业名称查询专业
	 */
	public Profession getByName(String name) {
		Criterion[] criterions = new Criterion[]{
				Restrictions.eq("name", name)
		};
		return findUniqueByCriteria(criterions);
	}

	public List<Profession> list(Profession profession) {
		Criteria criteria = this.createCriteria(this.createFilter(profession));
		return criteria.list();
	}

	public Page<Profession> findProfessions(Page<Profession> page,
			Profession filterProfession) {
		Criterion[] criterions = this.createFilter(filterProfession);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		if (0 < totalCount) {
			Criteria c = createCriteria(criterions);
			//c.addOrder(Order.asc("seq"));
			c.addOrder(Order.asc("id"));
			c = setPageParameter(c, page);
			@SuppressWarnings("unchecked")
			List<Profession> professions = c.list();
			page.setDataList(professions);
		}
		return page;
	}
	
	private Criterion[] createFilter(Profession profession) {
		if (null == profession) {
			return null;
		}
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (null != profession.getId()) {
			criterions.add(Restrictions.eq("id", profession.getId()));
		}
		if (!StringUtils.isBlank(profession.getName())) {
			criterions.add(Restrictions.like("name", profession.getName(), MatchMode.ANYWHERE));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}

	public List<Profession> list(int num) {
		StringBuffer querySql = new StringBuffer();
		querySql.append(" select * from t_profession p ORDER BY create_time limit ");
		querySql.append(num);
		SQLQuery query = this.createSqlQuery(querySql.toString(), null, null);
		query.addEntity(Profession.class);
		return query.list();
	}
	
}
